package service

import (
	"github.com/smash-llj/Nexa-server/global"
	"github.com/smash-llj/Nexa-server/models/request"
	"github.com/smash-llj/Nexa-server/models/response"
)

var fileService *FiledService

type FiledService struct {
	BaseService
}

func NewFileService() *FiledService {
	if fileService == nil {
		return &FiledService{
			NewBaseService(),
		}
	}
	return fileService
}

// GetAllMessageFile 获取最近聊天的聊天文件 Service
func (f *FiledService) GetAllMessageFile(UserId int) ([]response.FileResp, error) {
	var summaries []response.FileResp
	err := f.Gorm.Table("message").
		Select("message.message_type, message.created_at, message.file_size, message.file_name, message.file_url, "+
			"COALESCE(send.username, `to`.username) AS send_name").
		Joins("LEFT JOIN user AS send ON send.id = message.send_id").
		Joins("LEFT JOIN user AS `to` ON `to`.id = message.to_id").
		Where("message.send_id = ? OR message.to_id = ?", UserId, UserId).
		Where("message.message_type=?", global.MessageFile).
		Find(&summaries).Error
	if err != nil {
		return nil, err
	}
	return summaries, nil
}

// SearchMessageFile 查询最近聊天文件 Service
func (f *FiledService) SearchMessageFile(search request.SearchMessageFileReq) ([]response.FileResp, error) {
	var summaries []response.FileResp
	query := f.Gorm.Table("message").
		Select("message.message_type, message.created_at, message.file_size, message.file_name, message.file_url, "+
			"COALESCE(send.username, `to`.username) AS send_name").
		Joins("LEFT JOIN _user AS send ON send.id = message.send_id").
		Joins("LEFT JOIN user AS `to` ON `to`.id = message.to_id").
		Where("message.send_id = ? OR message.to_id = ?", search.UserId, search.UserId).
		Where("message_type = ?", global.MessageFile)

	// 如果 search.Filed 不为空，添加 file_name 的模糊查询
	if search.Filed != "" {
		query = query.Where("message.file_name LIKE ?", "%"+search.Filed+"%")
	}
	// 执行查询
	err := query.Find(&summaries).Error
	if err != nil {
		return nil, err
	}
	return summaries, nil
}
